package cn.org.gs.channel;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

// 通道之间传输数据
public class FileChannelDemo3 {
    public static void main(String[] args) throws Exception {
//        transferFromData();

        transferToData();

    }

    private static void transferFromData() throws Exception {
        // 创建两个FileChannel
        RandomAccessFile file1 = new RandomAccessFile("d:\\01.txt", "rw");
        FileChannel fromChannel = file1.getChannel();

        RandomAccessFile file2 = new RandomAccessFile("d:\\02.txt", "rw");
        FileChannel toChannel = file2.getChannel();

        // fromChannel 传输到 toChannel
        long position = 0;
        long size = fromChannel.size();

        toChannel.transferFrom(fromChannel, position, size);

        file1.close();
        file2.close();
        System.out.println("over！");

    }

    private static void transferToData() throws Exception {

        // 打开FileChannel
        RandomAccessFile file1 = new RandomAccessFile("d:\\01.txt", "rw");
        FileChannel fromChannel = file1.getChannel();

        RandomAccessFile file2 = new RandomAccessFile("d:\\02.txt", "rw");
        FileChannel toChannel = file2.getChannel();

        // fromChannel 传输到 toChannel
        long position = 0;
        long size = fromChannel.size();

        fromChannel.transferTo(position, size, toChannel);

        file1.close();
        file2.close();
        System.out.println("over！");
    }
}
